package com.example.sqliteapplication.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.example.sqliteapplication.AddressActivity;
import com.example.sqliteapplication.utils.AddressDBUtils;

public class QueryAddressService extends Service {
    public QueryAddressService() {
    }

    @Override
    public void onCreate() {
        Log.i("Main", "onCreate: start");
        TelephonyManager tm= (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        tm.listen(new MyPhoneListener(), PhoneStateListener.LISTEN_CALL_STATE);
    }

    @Override
    public void onDestroy() {
        Log.i("Main", "onCreate: destroy");
    }

    private class MyPhoneListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state){
                case TelephonyManager.CALL_STATE_RINGING:
                    String phone=incomingNumber;
                    Log.i("Address", "---------onCallStateChanged: "+incomingNumber);
                    String address= AddressDBUtils.findaddress(getApplicationContext(),phone);
                    Toast.makeText(getApplicationContext(),address,Toast.LENGTH_LONG).show();

            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
